﻿using BarManager.Core.ApplicationService.Interfaces;
using BarManager.Core.BusinessRules.Interfaces.Specification;
using BarManager.Core.BusinessRules.Interfaces.Validator;
using BarManager.Core.DomainModel;
using BarManager.Core.DomainService;
using BarManager.DependencyResolution.Web;
using BarManager.Infrastructure.Data;
using StructureMap;
using System.Web.Mvc;

namespace BarManager.DependencyResolution
{
    public static class Boot
    {
        public static void Initialize()
        {
            ObjectFactory.Initialize((config) =>
            {
                config.For<IObjectContext>().HttpContextScoped().Use<ObjectContext>();
                config.For<IUnitOfWork>().HttpContextScoped().Use(() => (IUnitOfWork)new StructureMapServiceLocator().GetService(typeof(IObjectContext)));

                config.Scan(scanner =>
                {                    
                    scanner.AssembliesFromApplicationBaseDirectory();
                    scanner.WithDefaultConventions();
                    scanner.AssemblyContainingType(typeof(IApplicationService<>));     
                    scanner.AssemblyContainingType(typeof(IRepository<>));
                    scanner.AssemblyContainingType(typeof(BaseRepository<>));
                    scanner.AssemblyContainingType(typeof(IValidator<>));
                    scanner.AssemblyContainingType(typeof(ISpecification<>));  
                    //scanner.Exclude(x => !x.Namespace.StartsWith("BarManager"));

                    scanner.ExcludeType<IObjectContext>();
                    scanner.ExcludeType<IUnitOfWork>();
                    scanner.AddAllTypesOf<IController>();
                });
            });

            Boot.InitMvc();
        }

        public static void Cleanup()
        {
            ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
        }

        private static void InitMvc()
        {
            DependencyResolver.SetResolver(new MvcDependencyResolver());
        }
    }
}
